package com.multi.tool.zip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 被压缩的字符长度不足会导致压缩后比压缩前的数据更大：例如 压缩前字节长度为：10，压缩后字节长度为：48
 */
public class GZipTest {

    public static void main(String[] args) throws IOException {
        unZip(compress("abc-abc-abc"));
    }

    /**
     * @return java.lang.String
     * @description : 数据压缩
     * @Param [msg]
     */
    public static String compress(String msg) throws IOException {
        //我这里用字节流输出的，所以转正byte[]
        byte[] b = msg.getBytes();
        System.out.println("压缩前长度：" + b.length);
        //缓存数据用的字节数组流
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        //压缩用的是这个流
        GZIPOutputStream gout = new GZIPOutputStream(bout);
        gout.write(b);//把b写入到缓冲区中，也就是ByteArrayOutputStream
        gout.close();//关闭流，也就是把数据全都刷到字节数组流中
        byte[] bytes = bout.toByteArray();
        System.out.println("压缩后长度：" + Arrays.toString(bytes).length());
        System.out.println("压缩后，转String：" + Arrays.toString(bytes));
        String compressMsg = new String(bytes, "ISO-8859-1");
        return compressMsg;
    }


    /**
     * @return java.lang.String 解压后的数据
     * @Param [compressMsg]  压缩后的数据
     */
    public static String unZip(String compressMsg) throws IOException {
        byte[] bytes = compressMsg.getBytes("ISO-8859-1");

        System.out.println("接收后：" + Arrays.toString(bytes));

        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

        GZIPInputStream gis = new GZIPInputStream(bis);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = -1;
        byte[] b1 = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while ((len = gis.read(b1)) != -1) {
            bos.write(b1, 0, len);
        }
        bos.close();
        System.out.println("解压之后：" + bos.toByteArray().length);
        return bos.toString();
    }

}
